package book;

/**
 * 生产者消费者模式
 * 一个生产者一个消费者
 * @author：涂有
 * @date 2017年2月28日 下午6:55:32
 */
public class ProducerConsumerTest {

	private static String value = "";
	
	static class Producer implements Runnable{
		
		public void run(){
			
			while(true){
				
				synchronized (ProducerConsumerTest.class) {
					
					if(!"".equals(value)){
						
						System.out.println(Thread.currentThread().getName() + "睡眠了");
						try {
							ProducerConsumerTest.class.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					
					value = System.currentTimeMillis() + "_" + System.nanoTime();
					System.out.println(Thread.currentThread().getName() + "生产：" + value);
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					ProducerConsumerTest.class.notifyAll();
				}
			}
		}
	}
	
	static class Consumer implements Runnable{
		
		public void run(){
			
			while(true){
				
				synchronized (ProducerConsumerTest.class) {
					
					if("".equals(value)){
						
						System.out.println(Thread.currentThread().getName() + "睡眠了");
						try {
							ProducerConsumerTest.class.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					
					System.out.println(Thread.currentThread().getName() + "消费：" + value);
					value = "";
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					ProducerConsumerTest.class.notifyAll();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		
		Producer p = new Producer();
		Consumer c = new Consumer();
		
		Thread tp = new Thread(p, "生产者1：");
		Thread tc = new Thread(c, "消费者1：");
		tp.start();
		tc.start();
	}
}
